package com.kujie.ai.controller;

import com.kujie.ai.service.DifyChatService;
import com.kujie.ai.utils.StreamUtils;
import io.github.guoshiqiufeng.dify.chat.DifyChat;
import io.github.guoshiqiufeng.dify.chat.dto.request.ChatMessageSendRequest;
import io.github.guoshiqiufeng.dify.chat.dto.response.ChatMessageSendCompletionResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerSentEvent;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.time.Duration;

/**
 * @author check
 * @date 2025-08-06
 */
@RestController
@RequestMapping("/dify")
@RequiredArgsConstructor
public class DifyController {
    @Autowired
    private DifyChatService difyChatService;

    @Autowired
    private DifyChat difyChat;

    @GetMapping(value = "/stream-chat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamChat(@RequestParam("input") String input) {
        return difyChatService.streamChat("app-XMNYILRQIU58k7X9DnhrX40k", "1", input);
    }

    @GetMapping("/events")
    public Flux<ServerSentEvent<String>> difyEvents(@RequestParam("input") String input) {
        ChatMessageSendRequest chatMessageSendRequest = new ChatMessageSendRequest();
        chatMessageSendRequest.setApiKey("app-XMNYILRQIU58k7X9DnhrX40k");
        chatMessageSendRequest.setContent(input);
        chatMessageSendRequest.setUserId("1");

        return StreamUtils.parseWorkflowOutput(difyChat.sendChatMessageStream(chatMessageSendRequest)).delayElements(Duration.ofMillis(150))
                .map(data -> ServerSentEvent.builder(data).build());
    }
}
